﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Configuration;
using VSM.Utils;

namespace VSM.Parts
{
    public partial class CreatePO : System.Web.UI.Page
    {

        private string TblHeaderName = "OPOR";
        private string TblLineName = "POR1";
        private string CurrentPageUrl = "/Business/Parts/Purchasing/CreatePO.aspx";
        private string HeaderKeyName = "DocEntry";

        private String TargetPageUrlGRPO = "/Business/Parts/Purchasing/GoodsReceiptPO.aspx";
        private String TargetPageUrlAPINV = "/Business/Parts/Purchasing/APInvoice.aspx";

        #region FileStreamObj
        protected Stream FileStreamObj
        {
            get { return (Stream)Session["FileStreamObj"]; }
            set { Session["FileStreamObj"] = value; }
        }
        #endregion

        #region FileLines
        protected ArrayList FileLines
        {
            get { return (ArrayList)ViewState["FileLines"]; }
            set { ViewState["FileLines"] = value; }
        }
        #endregion

        #region MRP
        private string _mrp = string.Empty;
        private string _mrpPOId = string.Empty;
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "Purchase Order";
            try
            {
                this.ucBP1.BPType = "S";
                this.ucBP1.LblInfo.Text = "Vendor";
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }
                //Convert MRPPO to actual PO
                if (Request.QueryString["MRPPO"] != null)
                {
                    _mrp = Request.QueryString["MRPPO"];
                }
                if (Request.QueryString["MRPPOID"] != null)
                {
                    _mrpPOId = Request.QueryString["MRPPOID"];
                }

                if (!IsPostBack)
                {
                    Session["LineDeleted"] = null;
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    ClearScreen();
                    // Get Warehouse
                    DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);

                    String poId = Request.QueryString["po_id"];
                    if (!String.IsNullOrEmpty(poId))
                    {
                        LoadData(poId, ConvertDocType.Get2String(DocType.PURCHASE_ORDER));
                        if (lblStatus.Text == "Closed")
                            SetScreenStatus("Close");
                        else if (lblStatus.Text == "O")
                            SetScreenStatus("Update");

                        //this.grvPO.Columns[11].Visible = false;
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }

                    String BaseEntry = Request.QueryString["base_entry"];
                    if (!String.IsNullOrEmpty(BaseEntry) || _mrpPOId.Length > 0)
                    {
                        String BaseType = Request.QueryString["base_type"];
                        LoadData(BaseEntry, BaseType);
                    }
                    if (Request.QueryString["mess"] != null)
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    }
                    if (Session[Utils.AppConstants.ID_Dealer].ToString() != "VSM")
                    {
                       // this.grvPO.Columns[11].Visible = false;
                        this.grvPO.Columns[12].Visible = false;
                        this.ddlVSMPOType.Visible = false;
                    }
                    else
                    {
                        this.ddlPOType.Visible = false;
                    }
                    if (this.ddlPOType.SelectedValue.ToString() == "1")
                    {
                        this.Panel1.Visible = true;
                        LoadDeposit();
                    }
                    else
                    {
                        this.Panel1.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadDeposit()
        {
            MasterData obj = new MasterData();
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataSet dsDeposit = obj.GetDepositActive(Session[Utils.AppConstants.ID_Dealer].ToString(), "VSM", Session[Utils.AppConstants.U_Department].ToString());
            if (dsDeposit != null && dsDeposit.Tables.Count > 0 && dsDeposit.Tables[0].Rows.Count > 0)
            {
                double Remain = 0;

                //DataSet dsOpenPO = obj.GetOpenPO(this.ucBP1.TxtCode.Text, dbType, Session[Utils.AppConstants.U_Department].ToString());
                //if (dsOpenPO != null && dsOpenPO.Tables.Count > 0)
                //{
                //    foreach (DataRow rGroup in dsOpenPO.Tables[0].Rows)
                //    {
                //        Remain += double.Parse(rGroup["Total"].ToString());
                //    }
                //}
                DataSet dsBP = obj.GetCustomerBalance(this.ucBP1.TxtCode.Text, "VSM", Session[Utils.AppConstants.U_Department].ToString());
                if (dsBP != null && dsBP.Tables.Count > 0)
                {
                    foreach (DataRow rGroup in dsBP.Tables[0].Rows)
                    {
                        Remain += double.Parse(rGroup["Balance"].ToString());
                    }
                }
                this.lblPer.Text = GF.FormatNumeric(Remain.ToString(), "SumDec");
                this.lblDeposit.Text = GF.FormatNumeric(dsDeposit.Tables[0].Rows[0]["DepositAmt"].ToString(), "SumDec");
                this.lblLimit.Text = GF.FormatNumeric(dsDeposit.Tables[0].Rows[0]["DepositLimit"].ToString(), "SumDec");
            }
            this.Panel1.Visible = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["POR1Table"];
                HiddenField hdnLineNum = (HiddenField)row.FindControl("hdnLineNum");
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {

                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        //Delete SAP
                        if (this.hdnIsLoadData.Value == "1")
                        {
                            DataTable tbDelete = new DataTable();
                            tbDelete.Columns.Add("LineNum");
                            if (Session["LineDeleted"] == null)
                            {
                                Session["LineDeleted"] = tbDelete;
                            }
                            else
                            {
                                tbDelete = (DataTable)Session["LineDeleted"];
                            }
                            DataRow r = tbDelete.NewRow();
                            r["LineNum"] = hdnLineNum.Value;
                            tbDelete.Rows.Add(r);
                            Session["LineDeleted"] = tbDelete;
                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvPO.EditIndex = -1;
                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }

                // Load Whs
                DropDownList ddlWhs = (DropDownList)e.Row.FindControl("ddlWhs");
                if (ddlWhs != null)
                {
                    ddlWhs.DataSource = dtWhs;
                    ddlWhs.DataValueField = "WhsCode";
                    ddlWhs.DataTextField = "WhsName";
                    ddlWhs.DataBind();
                    HiddenField hdnWhsCode = (HiddenField)e.Row.FindControl("hdnWhsCode");
                    if (hdnWhsCode != null) ddlWhs.SelectedValue = hdnWhsCode.Value;
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["POR1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvPO.EditIndex = -1;
                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtETD_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtETD = (TextBox)row.FindControl("txtETD");
                if (txtETD.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Estimate Time Delivery (ETD).');", true);
                    txtETD.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["U_ETD"] = txtETD.Text;
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtETA_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtETA = (TextBox)row.FindControl("txtETA");
                if (txtETA.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Estimate Time Arrival (ETA).');", true);
                    txtETA.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["U_ETA"] = txtETA.Text;
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDueDate_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDueDate = (TextBox)row.FindControl("txtDueDate");
                if (txtDueDate.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Estimate Time Arrival (ETA).');", true);
                    txtDueDate.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["U_DueDate"] = txtDueDate.Text;
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void BindData(DataTable tblData)
        {
            Session["POR1Table"] = tblData;
            this.grvPO.DataSource = tblData;
            this.grvPO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                    DataTable tblPOR1 = (DataTable)Session["POR1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblPOR1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    GetDefault defaultWS = new GetDefault();
                                    string priceType = string.Empty;
                                    if (this.ddlPOType.SelectedValue.ToString() == "0")
                                    {
                                        priceType = "3";
                                    }
                                    else
                                    {
                                        priceType = "4";
                                    }
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        LoadItem(poDate, ref  tblPOR1, dbType, item.Key, priceType, "1", "", "");
                                    }
                                    if (tblPOR1.Rows.Count > 0)
                                    {
                                        //Update Price
                                        foreach (DataRow dr in tblPOR1.Rows)
                                            updateRowTotalPrice(dr, "");
                                        CalcTotal(tblPOR1);
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblPOR1);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;
                            this.ucBP1.TxtCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.ucBP1.TxtName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.ucBP1.TxtCurrency.Text = ((HiddenField)row.FindControl("hdnCurrency")).Value;
                            if (tblPOR1 != null)
                            {
                                tblPOR1.Rows.Clear();
                            }
                            Session["ChosenBP"] = null;

                            this.btnAddItems.Visible = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string poId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(poId, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private void LoadItem(DateTime poDate, ref DataTable tblPOR1, string dbType, string key, string priceType
            , string quantity, string discount, string price)
        {
            GetDefault defaultWS = new GetDefault();
            MasterData obj = new MasterData();
            DataSet defaultInfo = null;
            DataSet dsDiscount = null;
            string cardCode = string.Empty;
            if (dbType != "VSM")
            {

                if (this.ddlPOType.SelectedValue.ToString() == "0")
                {
                    cardCode = "VSM-mO";
                }
                else if (this.ddlPOType.SelectedValue.ToString() == "1")
                {
                    cardCode = "VSM-eO";
                }
                else if (this.ddlPOType.SelectedValue.ToString() == "3" ||
                    this.ddlPOType.SelectedValue.ToString() == "4" ||
                    this.ddlPOType.SelectedValue.ToString() == "5")
                {
                    cardCode = "VSM-special";
                }
                else if (this.ddlPOType.SelectedValue.ToString() == "2")
                {
                    cardCode = "VSM-eO";
                }
            }
            try
            {
                defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                                             this.ucBP1.TxtCode.Text, key, 1, poDate, Utils.AppConstants.PARTS, priceType);
                if (dbType != "VSM")
                {
                    dsDiscount = obj.GetDealerDiscount(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), cardCode, key);
                }
            }
            catch
            {

            }
            if (defaultInfo != null && defaultInfo.Tables.Count > 0 && defaultInfo.Tables[0].Rows.Count > 0)
            {
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                DataRow rowNew = tblPOR1.NewRow();
                rowNew["No"] = (tblPOR1.Rows.Count + 1).ToString();
                rowNew["ItemCode"] = key;
                rowNew["Dscription"] = defaultInfo.Tables[0].Rows[0]["ItemName"];
                rowNew["U_Model"] = defaultInfo.Tables[0].Rows[0]["U_Model"];
                rowNew["unitMsr"] = defaultInfo.Tables[0].Rows[0]["UomCode"];
                rowNew["U_Product"] =
                rowNew["U_Color"] = string.Empty;
                rowNew["Quantity"] = quantity;
                rowNew["PriceBefDi"] = 0;
                if (discount.Length > 0)
                {
                    rowNew["DiscPrcnt"] = discount;
                }
                else
                {
                    if (dsDiscount != null && dsDiscount.Tables.Count > 0 && dsDiscount.Tables[0].Rows.Count > 0 && this.ddlPOType.SelectedValue.ToString() != "2")
                    {
                        rowNew["DiscPrcnt"] = GF.FormatNumeric(dsDiscount.Tables[0].Rows[0]["Discount"].ToString(), "PercentDec");
                    }
                    else
                    {
                        rowNew["DiscPrcnt"] = 0;
                    }
                }
                if (price.Length == 0)
                {
                    if (defaultInfo != null && defaultInfo.Tables.Count > 0 && defaultInfo.Tables[0].Rows.Count > 0)
                    {
                        rowNew["PriceBefDi"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
                    }
                    else
                    {
                        rowNew["PriceBefDi"] = 0;
                    }
                }
                else
                {
                    rowNew["PriceBefDi"] = price;
                }
                rowNew["TaxCode"] = "";
                rowNew["VatPrcnt"] = 0;
                rowNew["U_ETD"] = this.txtDelDate.Text.Trim();
                rowNew["U_ETA"] = this.txtDelDate.Text.Trim();
                rowNew["U_DueDate"] = this.txtDelDate.Text.Trim();
                rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

                rowNew["Available"] = GetAvailableQty(key);

                //DataRow[] rExist = tblPOR1.Select("ItemCode='" + key + "'");
                //if (rExist.Length == 0)
                //{
                //    tblPOR1.Rows.Add(rowNew);
                //}
                tblPOR1.Rows.Add(rowNew);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Can not found ItemCode.','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ItemCode"></param>
        /// <returns></returns>
        private string GetAvailableQty(string ItemCode)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            string lsSqlCommand = "select  (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) ))  As Available";
            lsSqlCommand += " From OITW where ItemCode = '" + ItemCode + "' and WhsCode In ('HCM-PAR', 'HN-PAR') ";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "Available");
        }
        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {
                //Update Price
                foreach (DataRow r in ((DataTable)Session["POR1Table"]).Rows)
                {
                    GetPrice(r);
                }
                BindData((DataTable)Session["POR1Table"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// Update Price
        /// </summary>
        /// <param name="r"></param>
        private void GetPrice(DataRow r)
        {
            try
            {
                DataSet ds = GetDataItem(DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.ucBP1.TxtCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }

                documentTotal += subTotal + gstTotal;
                this.lblDocumentTotal.Text = GF.FormatNumeric(documentTotal.ToString(), "SumDec");
                this.lblTaxAmount.Text = GF.FormatNumeric(gstTotal.ToString(), "SumDec");
                this.lblSubTotal.Text = GF.FormatNumeric(subTotal.ToString(), "SumDec");
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null;
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        private string CheckDate()
        {
            if (this.txtDelDate.Text.Trim().Length > 0 && this.txtPODate.Text.Trim().Length > 0)
            {
                if (Utils.AppConstants.isDateTime(this.txtPODate.Text) && Utils.AppConstants.isDateTime(this.txtDelDate.Text))
                {
                    if (Utils.AppConstants.ConvertToDate(this.txtPODate.Text).Date > Utils.AppConstants.ConvertToDate(this.txtDelDate.Text).Date)
                    {
                        return "Delivery Date cannot earliar than PO Issue Date.";
                    }
                }
                else
                {
                    return "PO Issue Date or Expected Delivery Date is incorrect format.";
                }
            }
            else
            {
                return "PO Issue Date or Expected Delivery Date is not Blank.";
            }
            return string.Empty;
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C") // || this.hdnIsCreatedSO.Value.Equals("true")
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscPrcnt = (TextBox)myRow.FindControl("txtDiscPrcnt");

                    TextBox txtETD = (TextBox)myRow.FindControl("txtETD");
                    ImageButton imgETD = (ImageButton)myRow.FindControl("imgETD");

                    TextBox txtETA = (TextBox)myRow.FindControl("txtETA");
                    ImageButton imgETA = (ImageButton)myRow.FindControl("imgETA");

                    TextBox txtDueDate = (TextBox)myRow.FindControl("txtDueDate");
                    ImageButton imgDueDate = (ImageButton)myRow.FindControl("imgDueDate");

                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;
                    if (imgETD != null) imgETD.Enabled = false;
                    if (imgETA != null) imgETA.Enabled = false;
                    if (imgDueDate != null) imgDueDate.Enabled = false;

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                    }
                    if (txtDiscPrcnt != null)
                    {
                        txtDiscPrcnt.ReadOnly = true;
                        txtDiscPrcnt.BackColor = System.Drawing.Color.Transparent;
                        txtDiscPrcnt.BorderStyle = BorderStyle.None;
                    }

                    if (txtETD != null)
                    {
                        txtETD.ReadOnly = true;
                        txtETD.BackColor = System.Drawing.Color.Transparent;
                        txtETD.BorderStyle = BorderStyle.None;
                    }

                    if (txtETA != null)
                    {
                        txtETA.ReadOnly = true;
                        txtETA.BackColor = System.Drawing.Color.Transparent;
                        txtETA.BorderStyle = BorderStyle.None;
                    }

                    if (txtDueDate != null)
                    {
                        txtDueDate.ReadOnly = true;
                        txtDueDate.BackColor = System.Drawing.Color.Transparent;
                        txtDueDate.BorderStyle = BorderStyle.None;
                    }
                }

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
                Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
            UpdatePrice();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtPostingDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtPODate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtPODate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtDelDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Delivery Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDelDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(this.ucBP1.TxtCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Vendor Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.ucBP1.TxtCode.Focus();
                    return;
                }

                MasterData obj = new MasterData();
                if (this.ddlPOType.SelectedValue.ToString() == "1")
                {
                    DataSet dsDeposit = obj.GetDepositActive(Session[Utils.AppConstants.ID_Dealer].ToString(), "VSM", Session[Utils.AppConstants.U_Department].ToString());
                    if (dsDeposit != null && dsDeposit.Tables.Count > 0 && dsDeposit.Tables[0].Rows.Count > 0)
                    {
                        double total = GF.Object2Double((object)GF.ResetFormatNumeric(this.lblDocumentTotal.Text), "SumDec");
                        DataSet dsOpenPO = obj.GetOpenPO(this.ucBP1.TxtCode.Text, dbType, Session[Utils.AppConstants.U_Department].ToString());
                        double Remain = 0;
                       
                        if (dsOpenPO != null && dsOpenPO.Tables.Count > 0)
                        {
                            foreach (DataRow rGroup in dsOpenPO.Tables[0].Rows)
                            {
                                Remain += double.Parse(rGroup["Total"].ToString());
                            }
                        }
                        total = total + Remain;
                        double r = double.Parse(dsDeposit.Tables[0].Rows[0]["DepositLimit"].ToString());
                        if (total > r)
                        {
                            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Grand Total cannot be greater than Deposit.');", true);
                            return;
                        }
                        else
                        {
                            double per = (r* 90) / 100;
                            if (total >= per)
                            {
                                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Grand Total equal 90% Deposit');", true);
                            }
                        }
                    }
                }

                String requestXML = _collectData();
                if (requestXML == "") return;
                Transaction ts = new Transaction();
                //Delete Line Item
                DataTable tbDelete = (DataTable)Session["LineDeleted"];
                if (tbDelete != null)
                {
                    if (tbDelete.Rows.Count > 0)
                    {
                        DataSet dsDelete = new DataSet();
                        DocumentXML xml = new DocumentXML();
                        dsDelete.Tables.Add(tbDelete.Copy());
                        DataSet dss = ts.RemoveMarketingDocumentLine(requestXML, ConvertDocType.Get2String(DocType.PURCHASE_ORDER), txtPONo.Text,
                        hdnIsUpdate.Value.Equals("true"), dbType, dsDelete, ConvertDocType.Get2String(DocType.PURCHASE_ORDER));
                        if ((int)dss.Tables[0].Rows[0]["ErrCode"] != 0)
                        {
                            Session["errorMessage"] = dss.Tables[0].Rows[0]["ErrMsg"];
                            Session["requestXML"] = requestXML;
                            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(dss.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                            return;
                        }
                        else
                        {
                            Session["LineDeleted"] = null;
                        }
                    }
                }
                //Update
                DataSet ds = new DataSet();
                ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.PURCHASE_ORDER), txtPONo.Text, hdnIsUpdate.Value.Equals("true"), dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["LineDeleted"] = null;
                    string lsPONo = txtPONo.Text;
                    string lsBuyerCode = ddlBuyer.SelectedValue;
                    string errorMess = obj.UpdatePOMRPStatus(_mrpPOId, dbType, (DataSet)Session["OpenOrderQty"]);
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                    if (this.ddlPOType.SelectedValue.ToString() == "1")
                    {
                        LoadDeposit();
                    }
                    if (!hdnIsUpdate.Value.Equals("true")) lsPONo = ds.Tables[0].Rows[0]["ErrMsg"].ToString();
                    #region send e-mail to Buyer Manager
                    if (!dbType.Equals("VSM")) SendMail(lsPONo, lsBuyerCode);
                    #endregion
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDiscount_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Taxcode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("WhsCode");
            // UDF
            dt.Columns.Add("U_ETD");
            dt.Columns.Add("U_ETA");
            dt.Columns.Add("U_DueDate");
            dt.Columns.Add("Available");


            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();

                    if (dtContent.Columns.Contains("LineNum")) row["LineNum"] = dr["LineNum"];

                    row["No"] = dr["No"];
                    row["Taxcode"] = dr["Taxcode"];

                    if (dtContent.Columns.Contains("ItemCode")) row["ItemCode"] = dr["ItemCode"];
                    if (dtContent.Columns.Contains("VatPrcnt")) row["VatPrcnt"] = dr["VatPrcnt"];
                    if (dtContent.Columns.Contains("Dscription")) row["Dscription"] = dr["Dscription"];

                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    if (dtContent.Columns.Contains("U_Color")) row["U_Color"] = dr["U_Color"];

                    row["unitMsr"] = dr["unitMsr"];
                    row["Quantity"] = dr["Quantity"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["Price"] = dr["Price"]; // Price After Discount
                    row["WhsCode"] = dr["WhsCode"];
                    // UDF
                    if (dtContent.Columns.Contains("U_ETD"))
                    {
                        row["U_ETD"] = string.IsNullOrEmpty(dr["U_ETD"].ToString()) ? this.txtDelDate.Text.Trim() : Convert.ToDateTime(dr["U_ETD"].ToString()).ToString(Utils.AppConstants.DATE);
                    }
                    else row["U_ETD"] = this.txtDelDate.Text.Trim();

                    if (dtContent.Columns.Contains("U_ETA")) row["U_ETA"] = string.IsNullOrEmpty(dr["U_ETA"].ToString()) ? this.txtDelDate.Text.Trim() : Convert.ToDateTime(dr["U_ETA"].ToString()).ToString(Utils.AppConstants.DATE);
                    else row["U_ETA"] = this.txtDelDate.Text.Trim();

                    if (dtContent.Columns.Contains("U_DueDate")) row["U_DueDate"] = string.IsNullOrEmpty(dr["U_DueDate"].ToString()) ? this.txtDelDate.Text.Trim() : Convert.ToDateTime(dr["U_DueDate"].ToString()).ToString(Utils.AppConstants.DATE);
                    else row["U_DueDate"] = this.txtDelDate.Text.Trim();

                    row["LineTotal"] = dr["LineTotal"];

                    if (dtContent.Columns.Contains("BaseType")) row["BaseType"] = dr["BaseType"];

                    if (dtContent.Columns.Contains("BaseEntry")) row["BaseEntry"] = dr["BaseEntry"];

                    if (dtContent.Columns.Contains("BaseLine")) row["BaseLine"] = dr["BaseLine"];

                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.txtRemarks.Text = "";
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDelDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPODate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPONo.Text =
            this.txtConpersonName.Text = string.Empty;
            this.ddlPOType.SelectedIndex = 0;
            this.ddlAppStatus.SelectedValue = "0";
            // Binding data Buyer
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");
            MasterData obj = new MasterData();
            DataSet dsBP = null;

            dsBP = obj.GetVendors("VSM", Session[Utils.AppConstants.ID_Dealer].ToString());
            if (dsBP != null && dsBP.Tables.Count > 0)
            {

                if (dbType.Equals(Utils.AppConstants.VSM))
                {
                    DataRow[] r = dsBP.Tables[0].Select("CardCode='" + "MC" + "'");
                    if (r.Length > 0)
                    {
                        this.ucBP1.TxtCode.Text = "MC";
                        this.ucBP1.TxtName.Text = "MITSUBISHI CORP.";
                        this.ucBP1.TxtCurrency.Text = r[0]["Currency"].ToString();
                    }
                }
                else
                {
                    DataRow[] r = dsBP.Tables[0].Select("CardCode='" + "VS" + "'");
                    if (r.Length > 0)
                    {
                        this.ucBP1.TxtCode.Text = "VS";
                        this.ucBP1.TxtName.Text = "VINA STAR MOTORS CORPORATION";
                        this.ucBP1.TxtCurrency.Text = r[0]["Currency"].ToString();
                    }
                }
            }

            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }
        protected void LoadData(String poId, string NewDocType)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            Transaction ts = new Transaction();

            //Hieu Edit - 1/22/1014 - START
            DataSet returnDoc = new DataSet();
            if (_mrp.Length == 0 && _mrpPOId.Length == 0)
            {
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, poId, dbType);
                if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);
                // Load Forecasts PO
                Session["FPOTable"] = GF.GetMasterListBySqlCommand(dbType, "select ROW_NUMBER() Over(Order By internal_id) No, * from tbl_ForecastPO where DocEntry = " + poId);
            }
            else
            {
                MasterData obj = new MasterData();
                returnDoc = obj.GetMRPPODataById(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), _mrpPOId);
            }

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];

            this.ucBP1.TxtCode.Text = dr["CardCode"].ToString();
            this.ucBP1.TxtName.Text = dr["CardName"].ToString();
            if (dtHeader.Columns.Contains("DocEntry"))
            {
                this.txtPONo.Text = dr["DocEntry"].ToString();
            }
            this.lblStatus.Text = dr["DocStatus"].ToString();

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtPODate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDelDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")));

            ddlPOType.Items.FindByValue("0").Selected = false;
            ddlPOType.Items.FindByValue("1").Selected = false;
            if (ddlPOType.Items.FindByValue(dr["U_SOType"].ToString()) != null)
                ddlPOType.Items.FindByValue(dr["U_SOType"].ToString()).Selected = true;
            else ddlPOType.SelectedIndex = 0;

            if (dtHeader.Columns.Contains("U_Updatestatus"))
            {
                ddlAppStatus.SelectedValue = dr["U_Updatestatus"].ToString();
            }
            else
            {
                ddlAppStatus.SelectedIndex = 0;
            }

            txtRemarks.Text = dr["Comments"].ToString();

            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.PURCHASE_ORDER))
                    SetScreenStatus("New");
                else SetScreenStatus("Update");
            }
            if (dtHeader.Columns.Contains("U_DHCCBG"))
            {
                if (dr["U_DHCCBG"].ToString().Equals("DHCC"))
                {
                    this.radPO.Checked = true;
                }
                if (dr["U_DHCCBG"].ToString().Equals("BG"))
                {
                    this.radSQRequest.Checked = true;
                }
            }
            // Binding data Buyer
            if (dtHeader.Columns.Contains("SlpCode"))
            {
                GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, dr["SlpCode"].ToString());
            }

            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            foreach (DataRow row in dtContents.Rows)
            {
                updateRowTotalPrice(row, "");
                if (ConvertDocType.Get2String(DocType.PURCHASE_ORDER) != NewDocType) //in this case is copy to
                {
                    row["BaseEntry"] = poId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                }
            }
            BindData(dtContents);
            updateTableTotalPrice();
        }
        protected void ClearScreen()
        {
            // Binding data Buyer
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");

            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Taxcode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("WhsCode");
            // UDF
            dt.Columns.Add("U_ETD");
            dt.Columns.Add("U_ETA");
            dt.Columns.Add("U_DueDate");
            dt.Columns.Add("Available");
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDelDate.Text.ToString(ci);
            txtPODate.Text.ToString(ci);
            txtPONo.Text =
            txtRemarks.Text =
            txtConpersonName.Text = string.Empty;
            this.lblSubTotal.Text =
            this.lblTaxAmount.Text =
            this.lblDocumentTotal.Text = "0";
            Session["LineDeleted"] = null;
            BindData(dt);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Enabled = true;
                    btnSave.Enabled = true;
                    btnCopyToGRPO.Enabled =
                    btnCopyToAPInvoice.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnIsCreatedSO.Value = "false";
                    this.hdnStatus.Value = "O";
                    this.hdnIsLoadData.Value = "0";
                    break;
                case "Update":
                    if (ddlAppStatus.SelectedValue.Equals("1"))
                    {
                        this.ucBP1.BtnSelect.Enabled =
                        btnAddItems.Enabled =
                        btnImport.Enabled =
                        btnSave.Enabled =
                        btnCancel.Enabled = false;
                        this.txtItemCode.Enabled = false;
                        btnCopyToGRPO.Enabled =
                        btnCopyToAPInvoice.Enabled = true;
                        hdnIsUpdate.Value = "false";
                        hdnIsCreatedSO.Value = "true";
                        this.hdnStatus.Value = "O";
                    }
                    else
                    {
                        this.ucBP1.BtnSelect.Enabled =
                        btnAddItems.Enabled =
                        btnImport.Enabled =
                        btnSave.Enabled =
                        btnCopyToGRPO.Enabled =
                        btnCopyToAPInvoice.Enabled = true;
                        hdnIsUpdate.Value = "true";
                        hdnIsCreatedSO.Value = "false";
                        this.hdnStatus.Value = "O";
                    }
                    this.hdnIsLoadData.Value = "1";
                    break;

                case "Close":
                    btnAddItems.Enabled =
                    btnSave.Enabled =
                    btnCopyToGRPO.Enabled =
                    btnCopyToAPInvoice.Enabled =
                    btnApprove.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnIsCreatedSO.Value = "false";
                    this.hdnStatus.Value = "C";
                    break;
            }
        }

        public String _collectData()
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                //dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series"); // 13
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("SlpCode");
                dtHeader.Columns.Add("Comments");
                // UDF
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("U_Updatestatus");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_DHCCBG");

                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true")) // Update
                {
                    //drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtPONo.Text);
                }
                else // Add new
                {
                    drHeader["Series"] = 13;
                    drHeader["DocStatus"] = "O";
                }

                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDelDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPODate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text;
                drHeader["CardCode"] = this.ucBP1.TxtCode.Text;
                drHeader["CardName"] = this.ucBP1.TxtName.Text;
                drHeader["SlpCode"] = ddlBuyer.SelectedValue;
                // UDF
                if (dbType != "VSM")
                {
                    drHeader["U_SOType"] = ddlPOType.SelectedValue;
                }
                else
                {
                    drHeader["U_SOType"] = this.ddlVSMPOType.SelectedValue;
                }
                drHeader["U_Updatestatus"] = (ddlAppStatus.SelectedValue == "2" ? "0" : ddlAppStatus.SelectedValue);
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;

                if (this.radPO.Checked)
                {
                    drHeader["U_DHCCBG"] = "DHCC";
                }
                if (this.radSQRequest.Checked)
                {
                    drHeader["U_DHCCBG"] = "BG";
                }

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;

                DataTable dtContents = (DataTable)Session["POR1Table"];
                DataTable dt = new DataTable(TblLineName);
                //dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                //dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("PriceBefDi");
                dt.Columns.Add("Price");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("unitMsr");
                //UDF
                dt.Columns.Add("U_ETD");
                dt.Columns.Add("U_ETA");
                dt.Columns.Add("U_DueDate");

                //dt.Columns.Add("LineTotal");

                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        //if (hdnIsUpdate.Value.Equals("true")) row["DocEntry"] = int.Parse(txtPONo.Text);
                        row["LineNum"] = liNo;
                        //row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["Quantity"] = dr["Quantity"];
                        row["PriceBefDi"] = dr["PriceBefDi"];
                        row["Price"] = dr["Price"]; // Price After Discount
                        row["WhsCode"] = dr["WhsCode"];
                        row["DiscPrcnt"] = dr["DiscPrcnt"];
                        row["unitMsr"] = dr["unitMsr"];
                        // UDF
                        row["U_ETD"] = Utils.AppConstants.ConvertToDate(dr["U_ETD"].ToString().Substring(0, 10)).ToString("yyyyMMdd");
                        row["U_ETA"] = Utils.AppConstants.ConvertToDate(dr["U_ETA"].ToString().Substring(0, 10)).ToString("yyyyMMdd");
                        row["U_DueDate"] = Utils.AppConstants.ConvertToDate(dr["U_DueDate"].ToString().Substring(0, 10)).ToString("yyyyMMdd");

                        //row["LineTotal"] = dr["LineTotal"];
                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                //Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "LineTotal" }; // Columns need to reset format numeric
                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price","DiscPrcnt" }; // Columns need to reset format numeric
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                Session["OpenOrderQty"] = ds;
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.PURCHASE_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        public String ApproveReject(string Updatestatus)
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("U_Updatestatus");

                DataRow drHeader = dtHeader.NewRow();
                drHeader["DocEntry"] = int.Parse(txtPONo.Text);
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["U_Updatestatus"] = Updatestatus;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.PURCHASE_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void updateTableTotalPrice()
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            double orderTotalBeforeDiscount = 0.0;
            double orderTotal = 0.0;
            double taxTotal = 0.0;
            DataTable dtContents = (DataTable)Session["POR1Table"];

            foreach (DataRow row in dtContents.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double(GF.ResetFormatNumeric(row["VatPrcnt"].ToString()), "RateDec");
                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;
                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;
                }
            }

            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal;
            this.lblDocumentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");
        }

        public String CollectDataSO()
        {
            try
            {
                //Update table header
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                DataTable dtContents = (DataTable)Session["POR1Table"];
                DataTable dtHeader = new DataTable("ORDR");
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series"); // 8
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("NumAtCard");
                dtHeader.Columns.Add("Comments");

                dtHeader.Columns.Add("GrosProfit");
                dtHeader.Columns.Add("VatSum");
                dtHeader.Columns.Add("DiscSum");
                dtHeader.Columns.Add("DiscPrcnt");

                // UDF
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("U_OrderConfirm");
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");


                DataRow drHeader = dtHeader.NewRow();
                drHeader["Series"] = 8;
                drHeader["DocStatus"] = "O";

                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDelDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPODate.Text).ToString("yyyyMMdd");
                drHeader["NumAtCard"] = txtPONo.Text;
                drHeader["Comments"] = txtRemarks.Text;
                MasterData masterDataWS = new MasterData();

                DataSet dsDealer = masterDataWS.GetDealerByID(Utils.AppConstants.VSM, Session[Utils.AppConstants.ID_Dealer].ToString());
                if (dsDealer != null & dsDealer.Tables[0].Rows.Count == 1)
                {
                    drHeader["CardCode"] = dsDealer.Tables[0].Rows[0]["CardCode"].ToString();
                    drHeader["CardName"] = dsDealer.Tables[0].Rows[0]["CardName"].ToString();
                    drHeader["U_ContactPerson"] = dsDealer.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                }

                drHeader["GrosProfit"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblSubTotal.Text) ? "0" : lblSubTotal.Text);
                drHeader["VatSum"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblTaxAmount.Text) ? "0" : lblTaxAmount.Text);
                drHeader["DiscSum"] =
                drHeader["DiscPrcnt"] = 0;
                // UDF
                drHeader["U_SOType"] = ddlPOType.SelectedValue;
                drHeader["U_OrderConfirm"] = "0";
                drHeader["U_DealerID"] = Utils.AppConstants.VSM;
                drHeader["U_Department"] = Utils.AppConstants.PARTS;
                dtHeader.Rows.Add(drHeader);

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "LineTotal" };

                DataSet ds = new DataSet("DS");
                dtHeader.TableName = "ORDR";
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable("RDR1");
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");

                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("ShipDate");
                dt.Columns.Add("Price");
                dt.Columns.Add("LineTotal");
                dt.Columns.Add("PriceBefDi");

                dt.Columns.Add("VatGroup");
                dt.Columns.Add("VatPrcnt");
                //
                dt.Columns.Add("VatSum");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_IncentiveDiscount");

                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Model");

                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    rowNew["LineNum"] = liNo;
                    rowNew["LineStatus"] = "O";
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["Price"] = dr["Price"];
                    rowNew["LineTotal"] = dr["LineTotal"];
                    rowNew["PriceBefDi"] = dr["PriceBefDi"];

                    rowNew["VatGroup"] = dr["VatGroup"];
                    rowNew["VatPrcnt"] = dr["VatPrcnt"];
                    rowNew["U_Discount"] =
                    rowNew["U_IncentiveDiscount"] = 0;

                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["U_Product"] = dr["U_Product"];
                    rowNew["U_Model"] = dr["U_Model"];

                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.SALES_ORDER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {

        }

        protected void btnReject_Click(object sender, EventArgs e)
        {

        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (ImportValidation())
            {
                string priceType = string.Empty;
                if (this.ddlPOType.SelectedValue.ToString() == "0")
                {
                    priceType = "3";
                }
                else
                {
                    priceType = "4";
                }
                //eO Price
                priceType = "4";
                DataTable dtExcelRecords = new DataTable();
                string fileLocation = Server.MapPath("~/App_Data/");
                if (this.FileUploadControl.HasFile)
                {
                    string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
                    this.FileUploadControl.SaveAs(fileLocation + fileName); // save file to server
                    dtExcelRecords = Utils.AppConstants.ImportCSVFile(fileName, fileLocation);
                }
                DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                DataTable tblRDR1 = (DataTable)Session["POR1Table"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                foreach (DataRow r in dtExcelRecords.Rows)
                {
                    LoadItem(poDate, ref tblRDR1, dbType, r["ItemCode"].ToString(), priceType, r["Quantity"].ToString(), r["DisCount"].ToString(), r["Price"].ToString());
                }

                if (tblRDR1.Rows.Count > 0)
                    foreach (DataRow dr in tblRDR1.Rows)
                        updateRowTotalPrice(dr, "");
                //ReLoad Data
                BindData(tblRDR1);
                updateTableTotalPrice();
            }
        }

        private bool ImportValidation()
        {

            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if ((!lsFileExtension.Equals(".csv")))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnCopyToGRPO_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrlGRPO + "?base_type=" + ConvertDocType.Get2String(DocType.PURCHASE_ORDER) + "&base_entry=" + txtPONo.Text);
        }

        protected void btnCopyToAPInvoice_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrlAPINV + "?base_type=" + ConvertDocType.Get2String(DocType.PURCHASE_ORDER) + "&base_entry=" + txtPONo.Text);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsPONo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.PURCHASE_ORDER),
                TblHeaderName, HeaderKeyName
            );
            if (txtPONo.Text.CompareTo(lsPONo) != 0) Response.Redirect(CurrentPageUrl + "?po_id=" + lsPONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlWhs_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlWhs = (DropDownList)row.FindControl("ddlWhs");
                if (ddlWhs.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a warehouse');", true);
                    ddlWhs.Focus();
                    return;
                }

                HiddenField hdnWhsCode = (HiddenField)row.FindControl("hdnWhsCode");
                if (hdnWhsCode != null && !string.IsNullOrEmpty(hdnWhsCode.Value))
                {
                    hdnWhsCode.Value = ddlWhs.SelectedValue;
                    DataTable tblPOR1 = (DataTable)Session["POR1Table"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblPOR1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0) rowUpdate[0]["WhsCode"] = hdnWhsCode.Value;
                    BindData(tblPOR1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.ucBP1.TxtCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblPOR1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            if (_mrp.Length == 0 && _mrpPOId.Length == 0) rowUpdate[0]["Quantity"] = 1;

                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            //rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];
                            rowUpdate[0]["TaxCode"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];
                            rowUpdate[0]["WhsCode"] = drDefaultLine["WhsCode"];
                            //
                            rowUpdate[0]["U_ETD"] = this.txtDelDate.Text;
                            rowUpdate[0]["U_ETA"] = this.txtDelDate.Text;
                            rowUpdate[0]["U_DueDate"] = this.txtDelDate.Text;


                            updateRowTotalPrice(rowUpdate[0], "");
                        }
                    }
                }
                else
                {
                    rowUpdate = tblPOR1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    if (_mrp.Length == 0 && _mrpPOId.Length == 0) rowUpdate[0]["Quantity"] = 1;

                    rowUpdate[0]["PriceBefDi"] = 0;
                    //rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["TaxCode"] = string.Empty;
                    rowUpdate[0]["VatPrcnt"] = 0;
                    rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                    // UDF
                    rowUpdate[0]["U_ETD"] =
                    rowUpdate[0]["U_ETA"] =
                    rowUpdate[0]["U_DueDate"] = this.txtDelDate.Text;

                    updateRowTotalPrice(rowUpdate[0], "");
                }
                BindData(tblPOR1);
                updateTableTotalPrice(); // Update total Amount
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
            DataTable tbPOR1 = (DataTable)Session["POR1Table"];
            DataRow rowNew = tbPOR1.NewRow();
            rowNew["No"] = (tbPOR1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["PriceBefDi"] = 0;
            rowNew["DiscPrcnt"] = 0;
            rowNew["PriceBefDi"] = 0;
            rowNew["TaxCode"] = string.Empty;
            rowNew["VatPrcnt"] = 0;
            rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
            // UDF
            rowNew["U_ETD"] =
            rowNew["U_ETA"] =
            rowNew["U_DueDate"] = this.txtDelDate.Text;

            tbPOR1.Rows.Add(rowNew);
            BindData(tbPOR1);
        }

        private void SendMail(string PONo, string BuyerCode)
        {
            if (ConfigurationManager.AppSettings["EmailActive"].ToString().CompareTo("0") == 0) return;

            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                string MailContent = string.Empty, MailTitle = string.Empty;
                EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.POSubmitted, "en");

                MasterData obj = new MasterData();
                DataSet ds = obj.GetManagerBySaleManCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), BuyerCode);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    MailContent = CurMailGenerator.POSubmmitted(ds.Tables[0].Rows[0]["SlpName"].ToString(), PONo, ConfigurationManager.AppSettings["VSM_URL"].ToString());
                    MailTitle = CurMailGenerator.MailTitle;
                    string[] tos = new string[] { ds.Tables[0].Rows[0]["U_Email"].ToString() };
                    Emails.SendEmail(tos, MailTitle, MailContent, null, null);
                }
            }
            catch (Exception ex)
            {
                // Add eeror to log.
            }
        }

        protected void btnForecast_Click(object sender, EventArgs e)
        {
            string popup = "OpenFCPO('" + txtPONo.Text + "')";
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPOType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            GetDefault defaultWS = new GetDefault();
            string priceType = string.Empty;
            string cardCode = string.Empty;
            if (this.ddlPOType.SelectedValue.ToString() == "0")
            {
                priceType = "3";
                cardCode = "VSM-mO";
            }
            else if (this.ddlPOType.SelectedValue.ToString() == "1")
            {
                priceType = "4";
                cardCode = "VSM-eO";
            }
            else if (this.ddlPOType.SelectedValue.ToString() == "3"||
                this.ddlPOType.SelectedValue.ToString() == "4"||
                this.ddlPOType.SelectedValue.ToString() == "5")
            {
                priceType = "4";
                cardCode = "VSM-special";
            }
            else if (this.ddlPOType.SelectedValue.ToString() == "2")
            {
                priceType = "4";
                cardCode = "VSM-eO";
            }
            //eO Price
            priceType = "4";
            MasterData obj = new MasterData();

            if (priceType.Length > 0)
            {

                foreach (DataRow r in tblPOR1.Rows)
                {
                    DataSet dsDiscount = obj.GetDealerDiscount(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), cardCode, r["ItemCode"].ToString());
                    DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                      this.ucBP1.TxtCode.Text, r["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS, priceType);
                    if (defaultInfo != null && defaultInfo.Tables.Count > 0 && defaultInfo.Tables[0].Rows.Count > 0)
                    {
                        r["PriceBefDi"] = GF.FormatNumeric(defaultInfo.Tables[0].Rows[0]["UnitPrice"].ToString(), "PriceDec"); ;
                    }
                    else
                    {
                        r["PriceBefDi"] = 0;
                    }

                    if (dsDiscount != null && dsDiscount.Tables.Count > 0 && dsDiscount.Tables[0].Rows.Count > 0
                        && this.ddlPOType.SelectedValue.ToString()!="2")
                    {
                        r["DiscPrcnt"] = GF.FormatNumeric(dsDiscount.Tables[0].Rows[0]["Discount"].ToString(), "PercentDec");
                    }
                    else
                    {
                        r["DiscPrcnt"] = 0;
                    }
                    updateRowTotalPrice(r, "");
                }
                BindData(tblPOR1);
                updateTableTotalPrice();
            }
            if (this.ddlPOType.SelectedValue.ToString() == "1")
            {
                LoadDeposit();
            }
            else
            {
                this.Panel1.Visible = false;
            }
        }

        protected void btnGetImportTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = Server.MapPath(SupportDocs.fileImportParts);
                string downloadName = "Parts.csv";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName + "");
                Response.ContentType = "text/csv";
                Response.TransmitFile(filePath);
                Response.End();
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            string openWindown = "OpenMain()";
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", openWindown, true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtItemCode_TextChanged(object sender, EventArgs e)
        {
            string priceType = string.Empty;
            if (this.ddlPOType.SelectedValue.ToString() == "0")
            {
                priceType = "3";
            }
            else
            {
                priceType = "4";
            }
            //eO Price
            priceType = "4";
            DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
            DataTable tblRDR1 = (DataTable)Session["POR1Table"];
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            LoadItem(poDate, ref tblRDR1, dbType, this.txtItemCode.Text.Trim(), priceType, "1", "", "");

            if (tblRDR1.Rows.Count > 0)
            {
                foreach (DataRow dr in tblRDR1.Rows)
                {
                    updateRowTotalPrice(dr, "");
                }
            }

            BindData(tblRDR1);
            updateTableTotalPrice();
            this.txtItemCode.Text = "";
            this.txtItemCode.Focus();
        }

        protected void ddlVSMPOType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearScreen();
        }
    }
}